package leetcode;

/**
 * 动态规划：编辑距离
 */
public class Solution68 {
    public int minDistance(String word1, String word2) {
        int length1 = word1.length();
        int length2 = word2.length();
        //创建dp数组
        int[][] dp = new int[length1+1][length2+1];
        //dp数组初始化
        for(int i = 1;i <= length1;i++){
            dp[i][0] = i;
        }
        for(int j = 1;j <= length2;j++){
            dp[0][j] = j;
        }
        //for循环遍历
        for(int i = 1;i <= word1.length();i++){
            for(int j = 1;j <= word2.length();j++){
                if(word1.charAt(i-1) == word2.charAt(j-1)){
                    dp[i][j] = dp[i-1][j-1]; //延续之前的状态
                }else{
                    dp[i][j] = Math.min(Math.min(dp[i-1][j]+1,dp[i][j-1]+1),dp[i-1][j-1]+1);
                }
            }
        }
        return dp[length1][length2];
    }
}
